package logic

import (
	"context"
	"jdshopuser/user_srv/user"

	"jdshopuser/api/internal/svc"
	"jdshopuser/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginUserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginUserLogic {
	return &LoginUserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginUserLogic) LoginUser(req *types.LoginByUsernameRequest) (resp *types.RegMsgResponse, err error) {
	// todo: 用户By账户密码登录

	//查询用户信息
	info, err := l.svcCtx.UserSrv.GetUsernameInfo(l.ctx, &user.UserByUsernameRequest{Username: req.Username})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:   -2,
			Msg:   "服务器错误",
			Datra: nil,
		}, err
	}
	if !(info.Password == req.Password) {
		return &types.RegMsgResponse{
			Cre:   -3,
			Msg:   "账户或密码错误",
			Datra: nil,
		}, err
	}

	_, err = l.svcCtx.UserSrv.LoginUsername(l.ctx, &user.LoginByUsernameRequest{
		Username: req.Username,
		Password: req.Password,
	})
	if err != nil {
		return &types.RegMsgResponse{
			Cre:   -1,
			Msg:   "服务器错误",
			Datra: nil,
		}, err
	}

	return &types.RegMsgResponse{
		Cre:   0,
		Msg:   "登录成功",
		Datra: nil,
	}, err
}
